<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图书馆座位预约系统 - 个人中心</title>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
        }
        body {
            background-color: #f0f8ff;
            min-height: 100vh;
            color: #333;
            display: flex;
            flex-direction: column;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            flex: 1;
        }
        .main-header {
            background-color: rgba(255, 255, 255, 0.95);
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            padding: 15px 0;
        }
        .header-container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .logo {
            display: flex;
            align-items: center;
            gap: 10px;
            font-size: 1.5rem;
            font-weight: bold;
            color: #1a2a6c;
        }
        .main-nav ul {
            display: flex;
            list-style: none;
            gap: 20px;
        }
        .main-nav a {
            text-decoration: none;
            color: #333;
            padding: 8px 15px;
            border-radius: 5px;
            transition: background-color 0.3s;
        }
        .main-nav a:hover, .main-nav li.active a {
            background-color: #1a73e8;
            color: white;
        }
        .user-info {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        .welcome {
            font-weight: 500;
        }
        .main-content {
            flex: 1;
            padding: 20px 0;
        }
        .profile-container {
            display: flex;
            gap: 30px;
        }
        .profile-sidebar {
            flex: 0 0 300px;
        }
        .profile-content {
            flex: 1;
        }
        .user-card {
            background-color: rgba(255, 255, 255, 0.95);
            border-radius: 12px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            padding: 25px;
            margin-bottom: 30px;
            text-align: center;
        }
        .profile-avatar {
            font-size: 4rem;
            color: #1a2a6c;
            margin-bottom: 15px;
        }
        .user-name {
            color: #1a2a6c;
            margin-bottom: 10px;
            font-size: 1.5rem;
        }
        .user-id {
            color: #7f8c8d;
            margin-bottom: 20px;
        }
        .profile-nav ul {
            list-style: none;
        }
        .profile-nav li {
            margin-bottom: 5px;
        }
        .profile-nav a {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 15px 20px;
            text-decoration: none;
            color: #333;
            border-radius: 8px;
            transition: all 0.3s;
        }
        .profile-nav a:hover, .profile-nav li.active a {
            background-color: #1a73e8;
            color: white;
        }
        .profile-section {
            background-color: rgba(255, 255, 255, 0.95);
            border-radius: 12px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            padding: 25px;
            margin-bottom: 30px;
        }
        .section-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 25px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eee;
        }
        .section-header h2 {
            color: #1a2a6c;
            font-size: 1.5rem;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-weight: 500;
            transition: all 0.3s;
            font-size: 0.9rem;
        }
        .btn-primary {
            background: #1a73e8;
            color: white;
        }
        .btn-primary:hover:not(:disabled) {
            background: #0d62d9;
        }
        .info-form {
            display: flex;
            flex-direction: column;
            gap: 20px;
        }
        .form-row {
            display: flex;
            gap: 20px;
        }
        .form-group {
            flex: 1;
            display: flex;
            flex-direction: column;
        }
        .form-group.full-width {
            flex: 1 0 100%;
        }
        .form-group label {
            font-weight: 500;
            color: #1a2a6c;
            margin-bottom: 8px;
        }
        .form-group input, .form-group textarea, .form-group select {
            padding: 12px 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 1rem;
            transition: border-color 0.3s;
        }
        .form-group input:focus, .form-group textarea:focus, .form-group select:focus {
            outline: none;
            border-color: #1a73e8;
        }
        .form-group input:disabled, .form-group textarea:disabled, .form-group select:disabled {
            background-color: #f8f9fa;
            color: #7f8c8d;
        }
        .form-group textarea {
            min-height: 100px;
            resize: vertical;
        }
        .required label::after {
            content: " *";
            color: #e74c3c;
        }
        .error-message {
            color: #e74c3c;
            font-size: 0.85rem;
            margin-top: 5px;
            display: none;
        }
        .form-group.error input, .form-group.error textarea, .form-group.error select {
            border-color: #e74c3c;
        }
        @media (max-width: 768px) {
            .header-container, .profile-container, .form-row {
                flex-direction: column;
            }
        }
        .loading {
            opacity: 0.6;
            pointer-events: none;
        }
        .success-message {
            color: #28a745;
            font-size: 0.85rem;
            margin-top: 5px;
            display: none;
        }
        .btn:disabled {
            background-color: #6c757d;
            cursor: not-allowed;
        }
    </style>
</head>
<body>
<header class="main-header">
    <div class="header-container">
        <div class="logo"><span>图书馆座位预约系统</span></div>
        <nav class="main-nav">
            <ul>
                <li><a href="index.html">首页</a></li>
                <li><a href="seat-selection.html">座位选择</a></li>
                <li><a href="booking-management.html">预约查询</a></li>
                <li class="active"><a href="user-profile.html">个人中心</a></li>
            </ul>
        </nav>
        <div class="user-info">
            <span class="welcome" id="welcomeText">欢迎，加载中...</span>
            <button class="btn btn-secondary" onclick="logout()" style="margin-left: 10px; padding: 5px 10px; font-size: 0.8rem;">退出</button>
        </div>
    </div>
</header>

<main class="main-content">
    <div class="container profile-container">
        <aside class="profile-sidebar">
            <div class="user-card">
                <div class="profile-avatar"><i class="fa fa-user-circle-o"></i></div>
                <h3 class="user-name" id="sidebarUsername">加载中...</h3>
                <p class="user-id" id="sidebarUserid">学号：加载中...</p>
                <nav class="profile-nav">
                    <ul>
                        <li class="active"><a href="#personal-info">个人信息</a></li>
                        <li><a href="change-password.html">修改密码</a></li>
                        <li><a href="#" onclick="logout()">退出登录</a></li>
                    </ul>
                </nav>
            </div>
        </aside>

        <div class="profile-content">
            <section id="personal-info" class="profile-section">
                <div class="section-header">
                    <h2><i class="fa fa-id-card"></i> 个人信息</h2>
                    <button class="btn btn-primary edit-btn" id="editBtn">编辑</button>
                </div>
                <div class="section-content">
                    <form class="info-form" id="infoForm">
                        <!-- 用户名（学号）不可修改 -->
                        <div class="form-row">
                            <div class="form-group full-width">
                                <label>学号：</label>
                                <input type="text" id="username" disabled class="admin-only">
                            </div>
                        </div>

                        <!-- 可修改的个人信息 -->
                        <div class="form-row">
                            <div class="form-group">
                                <label>年级：</label>
                                <select id="grade" disabled>
                                    <option value="">请选择年级</option>
                                    <option value="大一">大一</option>
                                    <option value="大二">大二</option>
                                    <option value="大三">大三</option>
                                    <option value="大四">大四</option>
                                    <option value="研一">研一</option>
                                    <option value="研二">研二</option>
                                    <option value="研三">研三</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label>学历：</label>
                                <select id="education" disabled>
                                    <option value="">请选择学历</option>
                                    <option value="本科生">本科生</option>
                                    <option value="研究生">研究生</option>
                                </select>
                            </div>
                        </div>

                        <div class="form-row">
                            <div class="form-group">
                                <label>学院：</label>
                                <select id="college" disabled>
                                    <option value="">请选择学院</option>
                                    <option value="经济管理学院">经济管理学院</option>
                                    <option value="机电工程学院">机电工程学院</option>
                                    <option value="计算机科学与工程学院">计算机科学与工程学院</option>
                                    <option value="土木工程学院">土木工程学院</option>
                                    <option value="国际商学院">国际商学院</option>
                                    <option value="生命科学学院">生命科学学院</option>
                                    <option value="外国语学院">外国语学院</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label>专业：</label>
                                <select id="major" disabled>
                                    <option value="">请选择专业</option>
                                </select>
                            </div>
                        </div>

                        <div class="form-row">
                            <div class="form-group">
                                <label>手机号：</label>
                                <input type="tel" id="phone" disabled>
                            </div>
                            <div class="form-group">
                                <label>邮箱：</label>
                                <input type="email" id="email" disabled>
                            </div>
                        </div>

                        <div class="success-message" id="successMessage">个人信息更新成功</div>
                    </form>
                </div>
            </section>
        </div>
    </div>
</main>

<script>
    // 全局变量
    let currentUser = '';
    let isEditing = false;
    let originalData = {};

    // 学院-专业联动数据
    const majorMap = {
        "经济管理学院": ["经济学", "市场营销", "工商管理", "行政管理", "人力资源管理", "航空服务与艺术管理"],
        "机电工程学院": ["机械设计制造及其自动化", "自动化", "测控技术与仪器", "车辆工程", "智能制造工程"],
        "计算机科学与工程学院": ["计算机科学与技术", "软件工程", "网络工程", "人工智能"],
        "土木工程学院": ["土木工程", "工程管理", "建筑环境与能源应用工程"],
        "国际商学院": ["国际商务", "财务管理"],
        "生命科学学院": ["生物工程", "化学工程与工艺", "食品科学与工程", "环境工程", "生物技术"],
        "外国语学院": ["日语", "英语", "朝鲜语"]
    };

    // 页面加载初始化
    document.addEventListener('DOMContentLoaded', function() {
        currentUser = sessionStorage.getItem('currentUser');
        if (!currentUser) {
            alert('请先登录');
            window.location.href = 'login.html';
            return;
        }

        initializePage();
        loadUserInfo();
    });

    // 初始化页面
    function initializePage() {
        // 设置学院专业联动
        const collegeSel = document.getElementById('college');
        const majorSel = document.getElementById('major');

        collegeSel.addEventListener('change', function() {
            fillMajor(this.value, majorSel);
        });

        // 设置编辑按钮事件
        const editBtn = document.getElementById('editBtn');
        editBtn.addEventListener('click', toggleEditMode);
    }

    // 加载用户信息
    function loadUserInfo() {
        fetch(`http://localhost:8080/api/user/get-info?username=${currentUser}`)
            .then(response => response.json())
            .then(student => {
                //打印学生信息
                console.log('Student:', JSON.stringify(student, null, 2));
                // 更新页面显示
                document.getElementById('welcomeText').textContent = `欢迎，${student.username}同学`;
                document.getElementById('sidebarUsername').textContent = student.username || '用户';
                document.getElementById('sidebarUserid').textContent = `学号：${student.username}`;
                document.getElementById('username').value = student.username;

                // 保存原始数据
                originalData = {
                    grade: student.grade || '',
                    education: student.education || '',
                    college: student.college || '',
                    major: student.major || '',
                    phone: student.phone || '',
                    email: student.email || ''
                };

                // 填充表单数据
                fillFormData(student);
            })
            .catch(err => {
                console.error('Error loading user info:', err);
                alert('加载用户信息失败');
            });
    }

    // 填充表单数据
    function fillFormData(student) {
        document.getElementById('grade').value = student.grade || '';
        document.getElementById('education').value = student.education || '';
        document.getElementById('college').value = student.college || '';
        document.getElementById('phone').value = student.phone || '';
        document.getElementById('email').value = student.email || '';

        // 填充专业
        if (student.college) {
            fillMajor(student.college, document.getElementById('major'));
            document.getElementById('major').value = student.major || '';
        }
    }

    // 填充专业选项
    function fillMajor(college, majorSelect) {
        majorSelect.innerHTML = '<option value="">请选择专业</option>';

        if (college && majorMap[college]) {
            majorMap[college].forEach(major => {
                const option = document.createElement('option');
                option.value = major;
                option.textContent = major;
                majorSelect.appendChild(option);
            });
        }
    }

    // 切换编辑模式
    function toggleEditMode() {
        const editBtn = document.getElementById('editBtn');
        const editableFields = [
            'grade', 'education', 'college', 'major', 'phone', 'email'
        ];

        if (!isEditing) {
            // 进入编辑模式
            isEditing = true;
            editBtn.textContent = '保存';
            editBtn.disabled = false;

            // 启用可编辑字段
            editableFields.forEach(field => {
                const element = document.getElementById(field);
                if (element) element.disabled = false;
            });

        } else {
            // 保存模式
            if (!validateForm()) {
                alert('请填写所有必填字段');
                return;
            }

            // 显示加载状态
            editBtn.textContent = '保存中...';
            editBtn.disabled = true;
            document.getElementById('infoForm').classList.add('loading');

            // 收集修改的数据
            const updates = {};
            let hasChanges = false;

            editableFields.forEach(field => {
                const element = document.getElementById(field);
                if (element && element.value !== originalData[field]) {
                    updates[field] = element.value;
                    hasChanges = true;
                }
            });

            if (!hasChanges) {
                alert('没有检测到任何修改');
                exitEditMode();
                return;
            }

            // 发送更新请求
            fetch(`http://localhost:8080/api/user/update-info?username=${currentUser}`, {
                method: 'PATCH',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(updates)
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // 更新原始数据
                        Object.assign(originalData, updates);

                        // 显示成功消息
                        const successMessage = document.getElementById('successMessage');
                        successMessage.style.display = 'block';
                        setTimeout(() => {
                            successMessage.style.display = 'none';
                        }, 3000);
                    } else {
                        alert('更新失败: ' + data.message);
                    }
                })
                .catch(err => {
                    console.error('Error updating user info:', err);
                    alert('更新失败，请检查网络连接');
                })
                .finally(() => {
                    exitEditMode();
                });
        }
    }

    // 退出编辑模式
    function exitEditMode() {
        isEditing = false;
        const editBtn = document.getElementById('editBtn');
        editBtn.textContent = '编辑';
        editBtn.disabled = false;

        // 禁用所有字段
        const editableFields = ['grade', 'education', 'college', 'major', 'phone', 'email'];
        editableFields.forEach(field => {
            const element = document.getElementById(field);
            if (element) element.disabled = true;
        });

        document.getElementById('infoForm').classList.remove('loading');
    }

    // 验证表单
    function validateForm() {
        const requiredFields = ['grade', 'education', 'college', 'major', 'phone'];

        for (let field of requiredFields) {
            const element = document.getElementById(field);
            if (!element.value.trim()) {
                element.focus();
                return false;
            }
        }

        // 验证手机号格式
        const phone = document.getElementById('phone').value;
        const phoneRegex = /^1[3-9]\d{9}$/;
        if (!phoneRegex.test(phone)) {
            alert('请输入有效的手机号码');
            document.getElementById('phone').focus();
            return false;
        }

        // 验证邮箱格式（如果填写了邮箱）
        const email = document.getElementById('email').value;
        if (email && !isValidEmail(email)) {
            alert('请输入有效的邮箱地址');
            document.getElementById('email').focus();
            return false;
        }

        return true;
    }

    // 验证邮箱格式
    function isValidEmail(email) {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return emailRegex.test(email);
    }

    // 退出登录
    function logout() {
        sessionStorage.removeItem('currentUser');
        window.location.href = 'login.html';
    }
</script>
</body>
</html>